package com.five.controller;

import com.five.common.DataGridView;
import com.five.domain.SysPermission;
import com.five.service.PermissionService;
import com.five.vo.PermissionVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/admin/permission")
public class PermissionController {
    @Autowired
    private PermissionService permissionService;

    //加载权限页面左边菜单树
    @RequestMapping("/loadPermissionManagerLeftTreeJson")
    @PreAuthorize("hasPermission('/admin/permission/toPermissionManager',null)")
    public DataGridView loadMenuManagerLeftTreeJson(PermissionVo permissionVo){
        permissionVo.setType(1);
        return permissionService.loadLeftManagerPermissionTreeJson(permissionVo);
    }

    //加载权限列表
    @RequestMapping("/loadAllPermission")
    @PreAuthorize("hasPermission('/admin/permission/toPermissionManager',null)")
    public DataGridView loadAllMenu(PermissionVo permissionVo){
        permissionVo.setType(2);
        Page<Object> page = PageHelper.startPage(permissionVo.getPage(),permissionVo.getLimit());
        List<SysPermission> data = permissionService.queryAllPermission(permissionVo);
        return new DataGridView(page.getTotal(),data);
    }

    //添加权限
    @RequestMapping("/addPermission")
    @PreAuthorize("hasPermission('/admin/permission/addPermission','permission:add')")
    public DataGridView addMenu(PermissionVo permissionVo){
        try {
            permissionVo.setType(2);
            permissionService.addPermission(permissionVo);
            return DataGridView.ADD_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return DataGridView.ADD_ERROR;
        }
    }

    //修改权限
    @RequestMapping("/updatePermission")
    @PreAuthorize("hasPermission('/admin/permission/updatePermission','permission:update')")
    public DataGridView updateMenu(PermissionVo permissionVo){
        try {
            permissionService.updatePermission(permissionVo);
            return DataGridView.UPDATE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return DataGridView.UPDATE_ERROR;
        }
    }

    //删除权限
    @RequestMapping("/deletePermission")
    @PreAuthorize("hasPermission('/admin/permission/deletePermission','permission:delete')")
    public DataGridView deleteMenu(Integer id){
        try {
            permissionService.deletePermission(id);
            return DataGridView.DELETE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return DataGridView.DELETE_ERROR;
        }
    }
}
